<template>
  <div class="app-container">
    <div class="action-container">
      <!--
      <el-button @click.prevent="handleImportClueEvent()" disabled>导出<i class="el-icon--right"></i></el-button>
       -->
    </div>
    <div class="filter-container">
      <el-date-picker v-model="listQuery.time" class="filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" value-format="yyyy-MM-dd:hh-mm-ss" end-placeholder="结束日期" />
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="list" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="机关部门">
        <template slot-scope="scope">
          {{ scope.row.superviseAgency1 }}
        </template>
      </el-table-column>
      <el-table-column label="线索数量">
        <template slot-scope="scope">
          {{ 10 || scope.row.superviseAgency1 }}
        </template>
      </el-table-column>
      <el-table-column label="平均立案时长(天)">
        <template slot-scope="scope">
          {{ 1 || scope.row.superviseAgency2 }}
        </template>
      </el-table-column>
      <el-table-column label="平均审理时长(天)">
        <template slot-scope="scope">
          {{ 2 || scope.row.receiptTime }}
        </template>
      </el-table-column>
      <el-table-column label="平均审结时长(天)">
        <template slot-scope="scope">
          {{ 2 || scope.row.receiptTime }}
        </template>
      </el-table-column>
      <el-table-column label="平均总时长(天)">
        <template slot-scope="scope">
          {{ 3 || scope.row.disposalTime }}
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!--导入对话框-->
    <el-dialog title="导入节目" :visible.sync="showImportClueDialog" width="40%">
      <el-form ref="importClueForm" :model="clueFile" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
        <el-form-item label="上传文件" prop="title">
          <el-upload ref="upload" :action="importClueUrl" :auto-upload="false" :limit="1" accept=".xls;.xlsx" :on-exceed="exceedFileListSize">
            <el-button slot="trigger" size="small" type="primary">选取Excel文件</el-button>
            <div class="el-upload__tip">xlsx文件, 1M以内，格式见模板下载</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showImportClueDialog = false">取消</el-button>
        <el-button type="primary" @click="tryImportClueFile">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import { MessageBox } from 'element-ui'
import { getClueList } from '@/api/clue'
import { getDateString } from '@/utils'
import { getToken } from '@/utils/auth'
import { parseErrorMessage } from '@/utils/request'

export default {
  filters: {
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_lk_period: undefined
      },
      showImportClueDialog: false,
      importClueUrl: process.env.VUE_APP_BASE_API + '/api/flow/clues/import',
      importResult: {},
      showImportResultDialog: false
    }
  },
  created() {
    // 查询数据
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getClueList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data
        this.total = response.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      this.listQuery.f_lk_period = undefined
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleImportClueEvent() {
      this.showImportClueDialog = true
      this.$nextTick(() => {
        this.$refs['importClueForm'].clearValidate()
      })
    },
    exceedFileListSize(files, fileList) {
      fileList.pop()
      fileList.push(files[0])
    },
    tryImportClueFile() {
      // 此处仍使用validate机制，是为了以后对其他字段进行输入校验
      this.$refs['importClueForm'].validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length === 0) {
            this.$message.error('请选择Excel(*xls;*.xlsx)文件')
            return
          }

          const files = this.$refs.upload.uploadFiles
          for (const file of files) {
            const name = file.name.toLowerCase()
            if (!name.endsWith('.xls') && !name.endsWith('.xlsx')) {
              this.$message.error('文件格式错误，请上传xlxs文件')
              return
            }

            // 文件大小不超过10M
            if (file.size > 10485760) {
              this.$message.error('文件太大，请上传10M以内的文件')
              return
            }
          }

          // 自动从form中获取提交的字段（包括上传文件）
          const form = new FormData(this.$refs.importClueForm.$el) // 文件对象

          // XMLHttpRequest 对象
          const xhr = new XMLHttpRequest()
          xhr.open('post', this.importClueUrl, true)

          // 加入Token做鉴权，此处使用XMLHttpRequest方式，就是为了在header中能够携带token
          xhr.setRequestHeader('Authorization', getToken())

          const $this = this
          xhr.onload = function() {
            if (xhr.status === 401) {
              store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
              })
            } else if (xhr.status < 200 || xhr.status >= 300) {
              const error = parseErrorMessage(xhr.responseText)
              $this.$message.error(error || '上传文件失败')
            } else {
              $this.$refs.upload.clearFiles()
              $this.showImportClueDialog = false
              $this.showImportResultDialog = true
              $this.importResult = JSON.parse(xhr.responseText)
            }
          }

          xhr.onerror = function(xhr, e) {
            $this.$message.error('上传文件失败')
          }

          // 发送请求
          xhr.send(form)
        }
      })
    },
    handleCloseImportResultEvent() {
      this.showImportResultDialog = false
      this.fetchData()
    }
  }
}
</script>
